<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Search, Download, Refresh } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getSpecificationSheetList,
  getBrandNameById,
  judgeDownloadPermisson,
} from '@/api/xyybackend/getVoList.js'
import { useLangStore } from '@/stores/langStore'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
import EllipsisCell from '@/components/commons/EclipseCell.vue'
onMounted(async () => {
  try {
    const res = await Promise.all([
      getSpecificationSheetList(),
      getBrandNameById({ brandId: useLangStore().brandId || 0 }),
    ])

    rawData.value = res[0].rows
    if (res[1].data != 0) brandName.value = res[1].data
  } catch (error) {
    rawData.value = []
    brandName.value = ''
  }
  setKeyWord()
})
interface Specification {
  id: number
  brand: string
  application: string
  productSeries: string
  modelNumber: string
  brief: string
  zhFileUrl: string | null
  enFileUrl: string | null
  brandRowspan?: number
  applicationRowspan?: number
  productSeriesRowspan?: number
}

// 原始数据
const rawData = ref<Specification[]>([])

// 计算合并信息（基于全量数据）
const calculateSpans = (data: Specification[]) => {
  const brandMap = new Map<string, number>()
  const applicationMap = new Map<string, number>()
  const productSeriesMap = new Map<string, number>()

  data.forEach((item) => {
    brandMap.set(item.brand, (brandMap.get(item.brand) || 0) + 1)
    applicationMap.set(
      `${item.brand}_${item.application}`,
      (applicationMap.get(`${item.brand}_${item.application}`) || 0) + 1
    )
    productSeriesMap.set(
      `${item.brand}_${item.application}_${item.productSeries}`,
      (productSeriesMap.get(
        `${item.brand}_${item.application}_${item.productSeries}`
      ) || 0) + 1
    )
  })

  const seenBrands = new Set<string>()
  const seenapplications = new Set<string>()
  const seenproductSeries = new Set<string>()

  return data.map((item) => {
    const brandKey = item.brand
    const applicationKey = `${item.brand}_${item.application}`
    const productSeriesKey = `${item.brand}_${item.application}_${item.productSeries}`

    const result = { ...item }

    if (!seenBrands.has(brandKey)) {
      seenBrands.add(brandKey)
      result.brandRowspan = brandMap.get(brandKey) || 1
    } else {
      result.brandRowspan = 0
    }

    if (!seenapplications.has(applicationKey)) {
      seenapplications.add(applicationKey)
      result.applicationRowspan = applicationMap.get(applicationKey) || 1
    } else {
      result.applicationRowspan = 0
    }

    if (!seenproductSeries.has(productSeriesKey)) {
      seenproductSeries.add(productSeriesKey)
      result.productSeriesRowspan = productSeriesMap.get(productSeriesKey) || 1
    } else {
      result.productSeriesRowspan = 0
    }

    return result
  })
}

// 初始化数据
const mergedData = ref<Specification[]>(calculateSpans(rawData.value))
const loading = ref(false)
const brandName = ref('')
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
//将路由的信息给到keyWord
const setKeyWord = () => {
  if (route.params.modelNumber[0] == null || route.params == undefined) {
    return
  }
  searchKeyword.value = route.params.modelNumber[0].toString()
}
// 过滤数据 + 重新计算合并信息
const filteredData = computed(() => {
  /* let result = rawData.value

  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = rawData.value.filter(
      (item) =>
        item.brand.toLowerCase().includes(keyword) ||
        item.application.toLowerCase().includes(keyword) ||
        item.productSeries.toLowerCase().includes(keyword) ||
        item.modelNumber.toLowerCase().includes(keyword) ||
        item.brief.toLowerCase().includes(keyword)
    )
  } */
  let result = rawData.value

  if (searchKeyword.value) {
    // 拆分关键词，去空格，去重，过滤空
    const keywords = searchKeyword.value
      .split(',')
      .map((k) => k.trim())
      .filter((k) => k)

    if (keywords.length > 0) {
      // 创建正则：匹配任意一个关键词作为“整体”出现（支持单词边界）
      const regex = new RegExp(
        keywords
          .map((k) =>
            // 转义特殊字符，避免正则注入（如 . * + ? 等）
            k.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
          )
          .join('|'),
        'i' // 忽略大小写
      )

      result = rawData.value.filter(
        (item) =>
          regex.test(item.brand) ||
          regex.test(item.application) ||
          regex.test(item.productSeries) ||
          regex.test(item.modelNumber) ||
          regex.test(item.brief)
      )
    }
  }

  // 每次过滤后重新计算合并信息
  return calculateSpans(result)
})

// 分页数据 + 重新计算合并信息
const displayData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value

  const paginatedData = filteredData.value.slice(start, end)

  // 每次分页后重新计算合并信息
  return calculateSpans(paginatedData)
})

// 行合并方法
const objectSpanMethod = ({
  row,
  column,
}: {
  row: Specification
  column: any
}) => {
  if (column.property === 'brand' && row.brandRowspan !== undefined) {
    return { rowspan: row.brandRowspan, colspan: 1 }
  }
  if (
    column.property === 'application' &&
    row.applicationRowspan !== undefined
  ) {
    return { rowspan: row.applicationRowspan, colspan: 1 }
  }
  if (
    column.property === 'productSeries' &&
    row.productSeriesRowspan !== undefined
  ) {
    return { rowspan: row.productSeriesRowspan, colspan: 1 }
  }
  return { rowspan: 1, colspan: 1 }
}

// 操作方法
const handleSearch = () => {
  currentPage.value = 1
}

const resetSearch = () => {
  searchKeyword.value = ''
  currentPage.value = 1
}

const handleSearchClear = () => {
  handleSearch()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}
// 多语言消息
const messages = {
  zh: {
    title: '权限不足',
    message: '检测到您尚未拥有权限下载规格书。请通过“联系我们”页面联系我们，我们将尽快为您开通',
    tips:'我们已收到您的联系,正在加急通过您的申请,请稍等~',
  },
  en: {
    title: 'Access Denied',
    message: 'You do not have permission to download the specification sheet. Please contact us via the "Contact Us" page, and we will enable access for you shortly.',
    tips:'We have received your request and are expediting the approval process. Please stay tuned!'
  }
}
const currentLang = ref<'zh' | 'en'>('zh')
const toggleLanguage = (clickLang) => {
  currentLang.value = clickLang
}
const title = computed(() => messages[currentLang.value].title)
const message = computed(() => messages[currentLang.value].message)
const tips = computed(() => messages[currentLang.value].tips)
const downloadFile = async (url: string, filename: string,currentLang:string) => {
  toggleLanguage(currentLang)
  const res = await judgeDownloadPermisson()
  if (res.data.exist && !res.data.allowed) {
    ElMessage.info(tips.value)
    return
  } else if (!res.data.exist) {
    ElMessageBox.alert(
      message.value,
      title.value, // 标题
      {
        confirmButtonText: '去联系我们',
        cancelButtonText: '取消', // 如果需要取消按钮
        type: 'warning', // 可选：'success', 'warning', 'info', 'error'
        confirmButtonClass: 'el-button--primary', // 可自定义按钮类
      }
    )
      .then(() => {
        // 用户点击“去联系我们”后执行
        router.push('/contact')
      })
      .catch(() => {
        // 用户取消（如果配置了取消按钮）
        ElMessage.info('您取消了申请')
      })
  } else {
    //权限拥有直接下载
    ElMessage.success(`开始下载: ${filename}`)
    const link = document.createElement('a')
    link.href = url
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }
}

onMounted(() => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 800)
})

// 【核心】打包所有需要翻译的文本
const i18n = computed(() => {
  const isZh = useLangStore().currentLang === 'zh'
  return {
    // 页面标题
    page_title: isZh ? '产品规格书下载' : 'Product Datasheet Download',

    // 搜索相关
    search_placeholder: isZh
      ? '请输入品牌/型号搜索'
      : 'Enter brand/model to search',
    search_button: isZh ? '搜索' : 'Search',
    reset_button: isZh ? '重置' : 'Reset',

    // 表格列名
    col_brand: isZh ? '品牌' : 'Brand',
    col_application: isZh ? '应用场景' : 'Application',
    col_series: isZh ? '产品系列' : 'Product Series',
    col_model: isZh ? '产品型号' : 'Model Number',
    brief: isZh ? '简介' : 'brief',
    col_zh_version: isZh ? '中文版' : 'chinese',
    col_en_version: isZh ? '英文版' : 'english',
  }
})
</script>
<template>
  <div class="specification-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h1>{{ i18n.page_title }}</h1>
          <div class="search-tools">
            <el-input
              v-model="searchKeyword"
              :placeholder="i18n.search_placeholder"
              clearable
              style="width: 300px"
              @clear="handleSearchClear"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="handleSearch" :icon="Search">{{
              i18n.search_button
            }}</el-button>
            <el-button @click="resetSearch" :icon="Refresh">{{
              i18n.reset_button
            }}</el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="displayData"
        border
        stripe
        style="max-width: 100%; overflow: auto"
        v-loading="loading"
        :span-method="objectSpanMethod"
      >
        <el-table-column
          prop="brand"
          :label="i18n.col_brand"
          min-width="120"
          align="center"
        />
        <el-table-column
          prop="application"
          :label="i18n.col_application"
          min-width="150"
          align="center"
        />
        <el-table-column
          prop="productSeries"
          :label="i18n.col_series"
          min-width="150"
          align="center"
        />
        <el-table-column
          prop="modelNumber"
          :label="i18n.col_model"
          min-width="180"
          align="center"
        />
        <el-table-column
          prop="brief"
          :label="i18n.brief"
          min-width="150"
          align="center"
        >
          <template #default="scope">
            <EllipsisCell
              :content="scope.row.brief"
              :max-width="'150px'"
              :line-clamp="2"
              placement="top"
            />
          </template>
        </el-table-column>
        <el-table-column
          :label="i18n.col_zh_version"
          width="120"
          align="center"
        >
          <template #default="{ row }">
            <el-button
              v-if="row.zhFileUrl"
              type="primary"
              size="small"
              @click="
                downloadFile(row.zhFileUrl, `${row.modelNumber}_中文版.pdf`,'zh')
              "
              :icon="Download"
            >
              下载
            </el-button>
            <el-tag v-else type="info">暂无</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          :label="i18n.col_en_version"
          min-width="120"
          align="center"
        >
          <template #default="{ row }">
            <el-button
              v-if="row.enFileUrl"
              type="success"
              size="small"
              @click="
                downloadFile(row.enFileUrl, `${row.modelNumber}_英文版.pdf`,'en')
              "
              :icon="Download"
            >
              Download
            </el-button>
            <el-tag v-else type="info">暂无</el-tag>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-modelNumber:current-page="currentPage"
          v-modelNumber:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredData.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.specification-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
  text-align: center;
}

.search-tools {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  .el-table-colum {
    min-width: 50px;
  }

  .search-tools {
    width: 100%;
    flex-wrap: wrap;
  }

  .search-tools .el-input {
    width: 100% !important;
  }
}
</style>
